package com.io.file;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.io.IOException;

/**
 * @author xin.ding
 * @date 2021/3/10 16:46
 */
public class FileMonitor {

    public static void main(String[] args) throws Exception {


        usingFileAlterationMonitor();

    }

    public static void usingFileAlterationMonitor() throws IOException {
        //get the file object
        File inputFile = FileUtil.file("test.txt");
        String absolutePath = inputFile.getAbsolutePath();
        String parent = absolutePath.substring(0, absolutePath.indexOf("test.txt"));
        File parentDirectory = FileUtil.file(parent);
        FileAlterationObserver observer = new FileAlterationObserver(parentDirectory);
        observer.addListener(new FileAlterationListenerAdaptor() {
            @Override
            public void onDirectoryCreate(File file) {
                System.out.println("Folder created: " + file.getName());
            }

            @Override
            public void onDirectoryDelete(File file) {
                System.out.println("Folder deleted: " + file.getName());
            }

            @Override
            public void onFileCreate(File file) {
                System.out.println("File created: " + file.getName());
            }

            @Override
            public void onFileDelete(File file) {
                System.out.println("File deleted: " + file.getName());
            }
        });
        //create a monitor to check changes after every 500 ms
        FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);
        try {
            monitor.start();
            //create a new directory
            File newFolder = new File("test");
            File newFile = new File("test1");
            newFolder.mkdirs();
            Thread.sleep(1000);
            newFile.createNewFile();
            Thread.sleep(1000);
            FileDeleteStrategy.NORMAL.delete(newFolder);
            Thread.sleep(1000);
            FileDeleteStrategy.NORMAL.delete(newFile);
            Thread.sleep(1000);
            monitor.stop(10000);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
